<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!--  标题行    -->
      <el-row :gutter="20" style="margin: 0px -20px 20px 5px;">
        <el-col :span="21">
          <h1 class="my-heading">考试列表</h1>
        </el-col>
        <el-col :span="2"><el-button type="primary" @click="goPage1(0)"
            style="font-size: 16px">创建考试</el-button></el-col>
      </el-row>
      <!--  查询条件    -->
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="考试名称" prop="examName">
            <el-input v-model="state.queryForm.examName" clearable placeholder="请输入考试名称" />
          </el-form-item>
          <el-form-item label="参与组织" prop="studyGroup">
            <el-cascader v-model="state.queryForm.studyGroupIds" ref="cascaderAddr" style="width: 220px"
              :options="options1" filterable clearable @visible-change="handleVisibleChange" placeholder="请选择"
              @change="handleCascaderChange"
              :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }">
            </el-cascader>
          </el-form-item>
          <el-form-item label="参与岗位" prop="groupNames">
            <el-select @change="getItem1" v-model="state.queryForm.postNames" multiple filterable clearable
              collapse-tags collapse-tags-tooltip placeholder="请选择" style="width: 240px">
              <el-option v-for="item in postList" :key="item.postsString" :label="item.postName"
                :value="item.postName" />
            </el-select>
          </el-form-item>
          <el-form-item label="考试时间" prop="time">
            <el-date-picker v-model="state.queryForm.time" @change="change" type="datetimerange" range-separator="到"
              start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <!--            <el-button plain :disabled="multiple" icon="Delete" type="primary"-->
            <!--                       v-auth="'train_ksglExamList_del'" @click="handleDelete(selectObjs)">批量删除</el-button>-->
          </el-form-item>
        </el-form>
      </el-row>
      <!--      <el-row>-->
      <!--        <div class="mb8" style="width: 100%">-->
      <!--          <right-toolbar v-model:showSearch="showSearch" :export="'train_ksglExamList_export'"-->
      <!--                @exportExcel="exportExcel" class="ml10 mr20" style="float: right;"-->
      <!--            @queryTable="getDataList"></right-toolbar>-->
      <!--        </div>-->
      <!--      </el-row>-->
      <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
        @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <!--        <el-table-column prop="index" label="序号" width="80" />-->
        <el-table-column prop="examId" label="考试编号" show-overflow-tooltip width="200px" />
        <el-table-column prop="examName" label="考试名称" show-overflow-tooltip width="180px" />
        <el-table-column prop="examType" label="考试类型" :formatter="formatter" show-overflow-tooltip width="90px" />
        <el-table-column prop="examTimeState" label="考试状态" :formatter="formatter1" show-overflow-tooltip width="90px" />
        <el-table-column prop="specifyTimeStart" label="开考时间" show-overflow-tooltip width="160px" />
        <el-table-column prop="examTime" label="考试时长(分钟)" show-overflow-tooltip width="120px" />
        <el-table-column prop="postName" label="参与岗位" show-overflow-tooltip width="160px" />
        <el-table-column prop="groupName" label="参与组织" show-overflow-tooltip />
        <el-table-column prop="counts" label="参考人数" show-overflow-tooltip width="90px" />
        <el-table-column label="监考详情" width="100">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'train_ksglExamList_edit'"
              @click="goPage2(scope.row.examId, scope.row.examName)">详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="考试详情" width="100">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'train_ksglExamList_edit'"
              @click="goPage(scope.row.examId)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'train_ksglExamList_edit'"
              @click="goPage1(1, scope.row.examId)">编辑</el-button>
            <el-button icon="delete" text type="primary" v-auth="'train_ksglExamList_del'"
              @click="handleDelete(scope.row.examId)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip width="120px" />
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>
    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
  </div>
</template>

<script setup lang="ts" name="systemKsglExamList">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, deleteExam } from "/@/api/train/ksglExamList";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useRouter } from 'vue-router';
import { useDict } from '/@/hooks/dict';
import { ref } from "vue";
import { deptTree, getEditList, syspost } from "/@/api/train/kszlData";
import mittBus from "/@/utils/mitt";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
// 定义查询字典
const router = useRouter();
const time = ref('')
// 定义变量内容
const formDialogRef = ref()
const groupId = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
//学习组织数据
const options1 = ref<any[]>([]);
//学习岗位
const postList = reactive([])
//部门主键
const pkDept = ref()
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})
//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)
//挂载完毕
onMounted(() => {
  deptTreeList()
})
const change = (val: any) => {
  state.queryForm.specifyTimeStart = val[0]
  state.queryForm.specifyTimeEnd = val[1]
}
const formatter = (row: any) => {
  if (row.examType == 0) {
    return '正式考试'
  } else {
    return '模拟考试'
  }
}
const formatter1 = (row: any) => {
  if (row.examTimeState == 0) {
    return '任意时间'
  } else {
    return '指定时间'
  }
}
const getItem1 = (val: any) => {
  let arr = []
  postList.forEach(item => {
    for (let i = 0; i < val.length; i++) {
      if (item.postName == val[i]) {
        arr.push(item.postsString)
        // console.log('arr',arr)
      }
    }
  })
  state.queryForm.postIds = arr.join(',')
}
const handleCascaderChange = (item: any) => {
  if (item !== null) {
    state.queryForm.groupId = item.join('/')
    groupId.value = item[item.length - 1]
  }
  state.queryForm.studyPosts = []
  state.queryForm.postNames = []
};
//参考组织下拉框关闭事件
const handleVisibleChange = (isVisible: any) => {
  if (!isVisible) {
    if (cascaderAddr.value) {
      const checkedNodes = cascaderAddr.value.getCheckedNodes(); // 输出选中的节点信息
      groupId.value = checkedNodes[0].value
    }
    getPostList()
  }
};
//跳转页面--------考试详情
const goPage = (examId1: string) => {
  const examId = examId1
  // console.log('sendId---------',sendId)
  const path = '/train/ksglTranscript/index';
  const sendId1 = { examId }
  router.push({ path, query: sendId1 })
}
//跳转页面--------编辑
const goPage1 = (flag: number, examId: string) => {
  const sendId1 = { flag, examId }
  // console.log('bianji',examId)
  const path = '/train/ksglExamList/index1';
  router.push({ path, query: sendId1 })
}
//跳转页面--------监考情况
const goPage2 = (examId: string, examName: string) => {
  const sendId1 = { examId, examName }
  const path = '/train/ksglExamList/invigilation';
  router.push({ path, query: sendId1 })
}
// 参与组织
const deptTreeList = () => {
  deptTree().then((res) => {
    options1.value = res.data;
  });
};
//学习岗位
const getPostList = () => {
  postList.length = 0
  const num = groupId.value
  syspost(num).then((res: any) => {
    Object.assign(postList, res.data)
  });
}
// 清空搜索条件
const resetQuery = () => {
  state.queryForm.time = null
  state.queryForm.studyGroupIds = null
  state.queryForm.postNames = null
  state.queryForm.groupId = null
  state.queryForm.postIds = null
  state.queryForm.specifyTimeStart = null
  state.queryForm.specifyTimeEnd = null
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}
// 导出excel
const exportExcel = () => {
  downBlobFile('/train/ksglExamList/export', Object.assign(state.queryForm, { ids: selectObjs }), 'ksglExamList.xlsx')
}
// 删除操作
const handleDelete = async (examId: string) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }
  try {
    await deleteExam(examId);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>
<style lang="scss" scoped>
.my-heading {
  color: black;
  font-weight: bold;
  font-size: 26px;
  margin-bottom: 10px;
}
</style>